﻿using DbFactory;
using PlaneClean.Models;
using PlaneClean.Service;
using PlaneClean.ViewModels.PlayClean;
using PlaneCleanEntity;
using S7.Net;
using S7NETPLC;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Timers;
using System.Web;
using System.Web.Http;

namespace PlaneClean.Controllers.ManagerController
{

    /// <summary>
    /// 清洗工作
    /// </summary>
    public class CleanWorkController : ManagerController
    {
        /// <summary>
        /// 开始清洗
        /// </summary>
        /// <param name="request"></param>
        /// <param name="auto">是否自动</param>                      
        /// <param name="pId">飞机id</param>
        /// <param name="testName">试验名称</param>
        /// <returns></returns>
        [HttpPost]
        public BaseResponse CleanStart(BaseRequest<List<int>> request, string auto, int pId,string testName)
        {

            PLCConfig pc = new PLCConfig();
            Plc plc = S7NETPLC.S7NETFactory.PlcSingle(pc);
            if (!plc.IsConnected)
            {
                plc.Open();
            }
            BaseResponse res = new BaseResponse();
            t_handle_record hr = new t_handle_record();
            hr.h_pId = pId;
            hr.h_handle_time = DateTime.Now;
            hr.h_operator= (HttpContext.Current.Session[request.token] as LoginInfo).UserInfo.u_name;
            hr.h_name = testName;
            hr.h_sprinklerId = string.Join(",", request.body);
            if (auto == "auto")
            {
                List<int> skIdList = dbFactory.Db.Queryable<t_sprinkler>().Where(a => a.sk_type == "levelLeft" || a.sk_type == "levelRight")
                      .Select(a => a.sk_id).ToList();
                t_clean_plane cp = new t_clean_plane();
                foreach (var skId in request.body)
                {
                    if (skIdList.Contains(skId))
                    {
                        cp = dbFactory.Db.Queryable<t_clean_plane>().Where(a => a.sk_id == skId && a.p_id == pId).First();
                        if (cp != null)
                        {
                            hr.h_skPlace = cp.sk_id.Value.ToString()+":"+cp.sk_level_space.ToString()+",";
                            //传给控制器 让控制器先移动喷头位置
                          PlcHandle.WriteData(plc, "I", 0, 0, "Byte", hr.h_skPlace);
                        }
                    }
                }
            }
            //通知Plc开始清洗
           PlcHandle.WriteData(plc, "I", 0, 0, "Byte", hr.h_sprinklerId);

            hr.h_plc_controlCode = "";
            hr.h_memo = "开始清洗";
            //dbFactory.Db.Insertable(hr).ExecuteReturnIdentity();
            CleanWorkService.TimerStart();
            t_clean_record cr = new t_clean_record();
            cr.cr_start_time = DateTime.Now;
            cr.cr_name = testName;
            cr.cr_operator = (HttpContext.Current.Session[request.token] as LoginInfo).UserInfo.u_name;
            int id = dbFactory.Db.Insertable(cr).ExecuteReturnIdentity();
            CleanWorkService.cr_id = id;
            res.reason = string.Join(",", request.body);
            res.result = "OK";
            return res;
        }
        /// <summary>
        /// 结束清洗
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public BaseResponse CleanEnd(BaseRequest request, int pId, string testName)
        {
            var rp = CleanWorkService.rp;
            //结束清洗记录清洗日志生成清洗报告保存
            BaseResponse res = new BaseResponse();
            RainParamsResopnse rpr = new RainParamsResopnse();
            int currentCount = CleanWorkService.TimerEnd();
            t_handle_record hr = new t_handle_record();
            hr.h_pId = pId;
            hr.h_handle_time = DateTime.Now;
            hr.h_operator = (HttpContext.Current.Session[request.token] as LoginInfo).UserInfo.u_name;
            hr.h_name = testName;
            hr.h_plc_controlCode = "";
            hr.h_memo = "停止清洗";
            if (currentCount > 0)
            {
                rpr.environmentHumidity = rp.environmentHumidity / currentCount;
                rpr.environmentTemperature = rp.environmentTemperature / currentCount;
                rpr.rainGauge1 = rp.rainGauge1 / currentCount;
                rpr.rainGauge2 = rp.rainGauge2 / currentCount;
                rpr.rainGauge3 = rp.rainGauge3 / currentCount;
                rpr.rainGauge4 = rp.rainGauge4 / currentCount;
                rpr.rainGauge5 = rp.rainGauge5 / currentCount;
                rpr.sideRainPress = rp.sideRainPress / currentCount;
                rpr.sideRainRate = rp.sideRainRate / currentCount;
                rpr.topRainPressBig = rp.topRainPressBig / currentCount;
                rpr.topRainPressSmall = rp.topRainPressSmall / currentCount;
                rpr.topRainRateBig = rp.topRainRateBig / currentCount;
                rpr.topRainRateSmall = rp.topRainRateSmall / currentCount;
                rpr.waterPH = rp.waterPH / currentCount;
            }
            t_clean_record cr = dbFactory.Db.Queryable<t_clean_record>().First(a => a.cr_id == CleanWorkService.cr_id);
            if (cr == null)
            {
                res.reason = "清洗记录id=" + CleanWorkService.cr_id + "的记录不存在";
                return res;
            }
            cr.cr_end_time = DateTime.Now;
            cr.cr_environmentHumidity = rpr.environmentHumidity;
            cr.cr_environmentTemperature = rpr.environmentTemperature;
            cr.cr_rainGauge1 = rpr.rainGauge1;
            cr.cr_rainGauge2 = rpr.rainGauge2;
            cr.cr_rainGauge3 = rpr.rainGauge3;
            cr.cr_rainGauge4 = rpr.rainGauge4;
            cr.cr_rainGauge5 = rpr.rainGauge5;
            cr.cr_sideRainPress = rpr.sideRainPress;
            cr.cr_sideRainRate = rpr.sideRainRate;
            cr.cr_topRainPressBig = rpr.topRainPressBig;
            cr.cr_topRainPressSmall = rpr.topRainPressSmall;
            cr.cr_topRainRateBig = rpr.topRainRateBig;
            cr.cr_topRainRateSmall = rpr.topRainRateSmall;
            cr.cr_waterPH = rpr.waterPH;
            cr.memo = "";
            //dbFactory.Db.Insertable(hr).ExecuteReturnIdentity();
            dbFactory.Db.Updateable(cr).ExecuteCommand();
           
            CleanWorkService.currentCount = 0;
            res.result = "OK";
            return res;
        }
        /// <summary>
        /// 开始清洗的喷头
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public BaseResponse CleanStartSk(BaseRequest<List<int>> request, int pId, string testName)
        {

            BaseResponse res = new BaseResponse();
            t_handle_record hr = new t_handle_record();
            hr.h_pId = pId;
            hr.h_handle_time = DateTime.Now;
            hr.h_operator = (HttpContext.Current.Session[request.token] as LoginInfo).UserInfo.u_name;
            hr.h_name = testName;
            hr.h_sprinklerId = string.Join(",", request.body);
            hr.h_plc_controlCode = "";
            hr.h_memo = "开启喷头";
            //dbFactory.Db.Insertable(hr).ExecuteReturnIdentity();

            res.reason = string.Join(",", request.body);
            res.result = "OK";
            return res;
        }
        /// <summary>
        /// 停止清洗的喷头
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public BaseResponse CleanEndSk(BaseRequest<List<int>> request, int pId, string testName)
        {

            BaseResponse res = new BaseResponse();
            t_handle_record hr = new t_handle_record();
            hr.h_pId = pId;
            hr.h_handle_time = DateTime.Now;
            hr.h_operator = (HttpContext.Current.Session[request.token] as LoginInfo).UserInfo.u_name;
            hr.h_name = testName;
            hr.h_sprinklerId = string.Join(",", request.body);
            hr.h_plc_controlCode = "";
            hr.h_memo = "停止喷头";
            //dbFactory.Db.Insertable(hr).ExecuteReturnIdentity();


            res.reason = string.Join(",", request.body);
            res.result = "OK";
            return res;
        }
        /// <summary>
        /// 左右移动侧面喷头位置
        /// </summary>
        /// <param name="skId"></param>
        /// <param name="position"></param>
        /// <returns></returns>
        [HttpPost]
        public BaseResponse UpdateSkPosition(BaseRequest request, int skId, int position, int pId, string testName)
        {
            BaseResponse res = new BaseResponse();

            t_handle_record hr = new t_handle_record();
            hr.h_pId = pId;
            hr.h_handle_time = DateTime.Now;
            hr.h_operator = (HttpContext.Current.Session[request.token] as LoginInfo).UserInfo.u_name;
            hr.h_name = testName;
            hr.h_skPlace = skId + ":" + position;
            hr.h_plc_controlCode = "";
            hr.h_memo = "位移喷头";
            //dbFactory.Db.Insertable(hr).ExecuteReturnIdentity();



            //返回移动后的对应喷头的位置
            int resPosition = 10;
            res.reason = resPosition.ToString();
            res.result = "OK";
            return res;
        }
        /// <summary>
        /// 排空
        /// </summary>
        /// <param name="skGroup">排空喷头组</param>
        /// <returns></returns>
        [HttpPost]
        public BaseResponse DrainSk(BaseRequest request,string skGroup, int pId, string testName)
        {
            BaseResponse res = new BaseResponse();

            t_handle_record hr = new t_handle_record();
            hr.h_pId = pId;
            hr.h_handle_time = DateTime.Now;
            hr.h_operator = (HttpContext.Current.Session[request.token] as LoginInfo).UserInfo.u_name;
            hr.h_name = testName;
            hr.h_drainSk = skGroup;
            hr.h_plc_controlCode = "";
            hr.h_memo = "喷头排空";
            //dbFactory.Db.Insertable(hr).ExecuteReturnIdentity();

            res.reason = skGroup;
            res.result = "OK";
            return res;
        }
        /// <summary>
        /// 补水
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public BaseResponse ReplenishWater(BaseRequest request, int pId, string testName)
        {
            BaseResponse res = new BaseResponse();
            t_handle_record hr = new t_handle_record();
            hr.h_pId = pId;
            hr.h_handle_time = DateTime.Now;
            hr.h_operator = (HttpContext.Current.Session[request.token] as LoginInfo).UserInfo.u_name;
            hr.h_name = testName;
            hr.h_replenishWater = "补水";
            hr.h_plc_controlCode = "";
            hr.h_memo = "喷头补水";
            //dbFactory.Db.Insertable(hr).ExecuteReturnIdentity();

            res.result = "OK";
            return res;
        }
        /// <summary>
        /// 保持连接读取清洗相关返回参数
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public BaseResponse<RainParamsResopnse> GetRainParams(int pId, string testName)
        {
            CleanWorkService.lastGetRainParamsTime = DateTime.Now;
            CleanWorkService.currentCount++;
            var rp = CleanWorkService.rp;
            BaseResponse<RainParamsResopnse> res = new BaseResponse<RainParamsResopnse>();
            res.Body = new RainParamsResopnse();
            res.Body.environmentHumidity = 2;
            res.Body.environmentTemperature = 3;
            res.Body.rainGauge1 = 1;
            res.Body.rainGauge2 = 2;
            res.Body.rainGauge3 = 3;
            res.Body.rainGauge4 = 4;
            res.Body.rainGauge5 = 5;
            res.Body.sideRainPress = 50;
            res.Body.sideRainRate = 20;
            res.Body.topRainPressBig = 70;
            res.Body.topRainPressSmall = 30;
            res.Body.topRainRateBig = 25;
            res.Body.topRainRateSmall = 15;
            res.Body.waterPH = 6;



            rp.environmentHumidity += res.Body.environmentHumidity;
            rp.environmentTemperature += res.Body.environmentTemperature;
            rp.rainGauge1 += res.Body.rainGauge1;
            rp.rainGauge2 += res.Body.rainGauge2;
            rp.rainGauge3 += res.Body.rainGauge3;
            rp.rainGauge4 += res.Body.rainGauge4;
            rp.rainGauge5 += res.Body.rainGauge5;
            rp.sideRainPress += res.Body.sideRainPress;
            rp.sideRainRate += res.Body.sideRainRate;
            rp.topRainPressBig += res.Body.topRainPressBig;
            rp.topRainPressSmall += res.Body.topRainPressSmall;
            rp.topRainRateBig += res.Body.topRainRateBig;
            rp.topRainRateSmall += res.Body.topRainRateSmall;
            rp.waterPH += res.Body.waterPH;

            res.result = "OK";
            return res;
        }
    }
}